﻿const mqtt = require('mqtt');

// 使用更稳定的公共MQTT测试服务器
const brokerUrl = 'mqtt://test.mosquitto.org:1883';  // 或者 'mqtt://broker.emqx.io:1883'

// MQTT连接选项
const options = {
    clientId: 'andon-system-' + Math.random().toString(16).substr(2, 8),
    clean: true,
    connectTimeout: 4000,
    reconnectPeriod: 1000
};

const client = mqtt.connect(brokerUrl, options);

client.on('connect', () => {
    console.log('[MQTT] 成功连接到代理服务器');
});

client.on('error', (err) => {
    console.error('[MQTT] 连接错误:', err.message);
});

client.on('close', () => {
    console.log('[MQTT] 连接关闭');
});

client.on('offline', () => {
    console.log('[MQTT] 客户端离线');
});

client.on('reconnect', () => {
    console.log('[MQTT] 尝试重新连接...');
});

const sendNotification = (userId, message) => {
    if (client.connected) {
        const topic = 'factory/notifications/';
        client.publish(topic, JSON.stringify(message), { qos: 1 });
        console.log('[MQTT] 已发送通知给用户 : ');
    } else {
        console.log('[MQTT] 客户端未连接，无法发送通知');
    }
};

module.exports = { client, sendNotification };
